package main.com.oaer.action;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import main.com.oaer.model.Purview;
import main.com.oaer.service.PurviewService;
import main.com.oaer.util.CommonUtil;
import main.com.oaer.util.JsonPluginsUtil;

/**
 * 权限的控制器
 *
 */
@Controller
@RequestMapping("/purview")
public class PurviewAction {
	
	@Autowired
	PurviewService purviewService;
	
	/**
	 * 获取所有权限，进入权限树展示页面
	 * @param modelMap 模型map
	 * @return "system/listPreview" 权限树展示页面 
	 */
	@RequestMapping(value="/toList")
	public String entryList(ModelMap modelMap){
		List<Map<String, Object>> purviewsList = purviewService.findPurviews();
		modelMap.put("purviewsList", JsonPluginsUtil.listToJson(purviewsList));
		return "system/listPreview";
	}
	
	/**
	 * 进入增加权限页面
	 * @param pId  父权限的id
	 * @param modelMap 模型map
	 * @return "system/addPreview" 增加权限的页面
	 */
	@RequestMapping(value="/toAdd")
	public String entryAdd(Long pId,ModelMap modelMap){
		modelMap.put("pId",pId);
		return "system/addPreview";
	}
	
	/**
	 * 增加一个权限，以json格式异步返回消息
	 * @param response  回应对象
	 * @param purview 待插入的权限对象
	 */
	@RequestMapping(value="/add")
	public void add(HttpServletResponse response, Purview purview){
		purviewService.add(purview);
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("status", "success");
		CommonUtil.printToHTML(response, map);
	}
	
	/**
	 * 删除一个权限，以json格式异步返回消息
	 * @param response  回应对象
	 * @param id  权限id
	 */
	@RequestMapping(value="/delete")
	public void delete(HttpServletResponse response, Long id){
		Purview purview = purviewService.load(id);
		purviewService.delete(purview);
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("status", "success");
		CommonUtil.printToHTML(response, map);
	}
	
	/**
	 * 进入修改权限页面
	 * @param map  模型map
	 * @param id  权限id
	 * @return
	 */
	@RequestMapping(value="/toEdit")
	public String toEdit(ModelMap map,Long id){		
		map.put("purview",purviewService.load(id));
		return "system/updatePreview";
	}
	
	/**
	 * 修改一个权限，，以json格式异步返回消息
	 * @param response  回应对象
	 * @param purview 待修改的权限对象
	 */
	@RequestMapping(value="/update")
	public void update(HttpServletResponse response, Purview purview){
		purviewService.update(purview);
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("status", "success");
		CommonUtil.printToHTML(response, map);
	}
	
}
